import multiprocessing as mp
import yinghuazaixian
import json
import redis
import uuid
import time
import pymysql
# 导入Flask类
from flask import Flask,redirect,url_for
from flask import render_template
from flask import request
# 实例化，可视为固定格式
app = Flask(__name__)
r = redis.Redis(host='127.0.0.1', port=6379,db=0,decode_responses=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/wangke', methods=['GET'])
def wangke():
    return render_template('wangke.html')

@app.route('/weixin', methods=['GET'])
def weixin():
    return render_template('weixin.html', username=request.args.get("username"))

@app.route('/user')
def user():
    return render_template('user.html')

@app.route('/log', methods=['GET'])
def log():
    with open("./static/xinxi/app.log", 'r') as f:
        logs = f.readlines()[-50:]
    return render_template('log.html',logs=logs[::-1])


def mysql():
    db = pymysql.connect(host='192.168.30.32',
                     port=5306,
                     user='root',
                     password='123456',
                     database='wangke',
                     cursorclass=pymysql.cursors.DictCursor)
    return db

@app.route("/wangke", methods=['POST'])
def yinghua():
    key = request.form['key']
    course = request.form['course']
    username = request.form['username']
    password = request.form['password']
    school = request.form['school']
    if (request.method == 'POST') and r.get(key):
        if r.get(key) == str(len(course)):
            # 未使用过的卡密
            s = mp.Process(target=yinghuazaixian.run,args=(username,password,course,school,))
            s.start()
            with open("./static/xinxi/app.log", 'a') as f:
                f.write(str(username + "----pid: " + str(s.pid) + "\n"))
            db = mysql()
            cursor = db.cursor()
            if cursor.execute("select * from `user` where `username`=%s" % username) == 0:
                insertUser(username,password,course,school,key)
            usekey(key,username)
            return redirect(url_for('weixin',username=username))
        elif r.get(key) == username:
            sql = "select `state` from `user` where `username`=%s" % username
            db = mysql()
            cursor = db.cursor()
            if cursor.execute(sql):
                state = cursor.fetchone()
                state = state['state']
                if state == 0:
                    s = mp.Process(target=yinghuazaixian.run,args=(username,password,course,school,))
                    s.start()
                    with open("./static/xinxi/app.log", 'a') as f:
                        f.write(str(username + "----pid: " + str(s.pid) + "\n"))
                    return redirect(url_for('weixin',username=username))

                elif state == 2:
                    return "该账号已在运行"
                else:
                    return "该账号已学完"
                
        #print(username+"已运行")
        
    else:
        return "卡密不存在"
    return ""

@app.route("/supplement", methods=['GET'])
def supplement():
    if request.method == 'GET':
        sql = "select * from `user` where `username`=%s" % request.args.get("username")
        db = mysql()
        cursor = db.cursor()
        if cursor.execute(sql):
            user = cursor.fetchone()
            if user['state'] == 0:
                s = mp.Process(target=yinghuazaixian.run,args=(user['username'],user['password'],user['course'],user['school']),)
                s.start()
                with open("./static/xinxi/app.log", 'a') as f:
                    f.write(str(user['username'] + "----pid: " + str(s.pid) + "\n"))
                return user['username'] + "已成功运行"
            else:
                return user['username'] + "已在运行或者运行完成"
        else:
            return "账号不存在"


@app.route("/key", methods=['GET'])
def key():
    if (request.method == 'GET') and request.args.get("key") == "laotun":
        key = str(uuid.uuid1())
        r.set(key,request.args.get("s"),5*24*60*60)
        with open("./static/xinxi/key.txt", 'a') as f:
            f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "------" + key + "\n")
        return key

def usekey(key,username):
    r.setrange(key,0,username)

def insertUser(username,password,course,school,key):
    sql = "insert into `user`(`username`,`password`,`school`,`course`,`key`) \
           values(%s,%s,%s,%s,%s)"
    
    try:
        # 执行sql语句
        db = mysql()
        cursor = db.cursor()
        cursor.execute(sql,(username,password,school,course,key))
        # 提交到数据库执行
        db.commit()
        return 1
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()
        return 0

@app.route("/userall", methods=['POST'])
def queryAll():
    sql = "select * from `user`"
    
    try:
        # 执行SQL语句
        db = mysql()
        cursor = db.cursor()
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        return json.dumps(results)
    except:
        print ("Error: unable to fetch data")

if __name__ == '__main__':
    # app.run(host, port, debug, options)
    # 默认值：host=127.0.0.1, port=5000, debug=false
    app.run(host='0.0.0.0',port=5555)

# route()方法用于设定路由；类似spring路由配置
#等价于在方法后写：app.add_url_rule('/', 'helloworld', hello_world)
#@app.route('/helloworld')
#def hello_world():
#    return 'Hello, World!'

# 配置路由，当请求get.html时交由get_html()处理
#@app.route('/get.html')
#def get_html():
#    # 使用render_template()方法重定向到templates文件夹下查找get.html文件
#    return render_template('get.html')

# 配置路由，当请求post.html时交由post_html()处理
#@app.route('/post.html')
#def post_html():
#    # 使用render_template()方法重定向到templates文件夹下查找post.html文件
#    return render_template('post.html')

# 配置路由，当请求deal_request时交由deal_request()处理
# 默认处理get请求，我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
#@app.route('/deal_request', methods = ['GET', 'POST'])
#def deal_request():
#    if request.method == "GET":
#        # get通过request.args.get("param_name","")形式获取参数值
#        get_q = request.args.get("q","")
#        return render_template("result.html", result=get_q)
#    elif request.method == "POST":
#        # post通过request.form["param_name"]形式获取参数值
#        post_q = request.form["q"]
#        return render_template("result.html", result=post_q)
